var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var orm = require('orm');

var routes = require('./routes/index');
var user = require('./routes/users');
var order = require('./routes/order');
var kpi = require('./routes/kpi');
var product = require('./routes/product');
var member = require('./routes/member');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


var opts = {
  database : "bi_dw",
  protocol : "postgres",
  host     : "121.43.100.151",
  port     : 5432,         // optional, defaults to database default
  user     : "bi_etl",
  password : "Youayuns2016",
  query    : {
    pool     : true,   // optional, false by default
    debug    : false,   // optional, false by default
    strdates : true    // optional, false by default
  }
};

// 定义orm和数据库
app.use(orm.express(opts, {
  define: function (db, models, next) {
    models.trade_order_measure_daily = db.define("youa_dm.trade_order_measure_daily", {
      create_date:          Date,
      order_num:            Number,
      paid_order_num:       Number,
      member_num:           Number,
      paid_member_num:      Number,
      payment_amount:       Number,
      paid_payment_amount:  Number,
      pct:                  Number,
      etl_time:             Date,
      terminal_type:        String,
      cps_channel:          String,
      gross_margin:         Number
    },{
      id: "etl_time"
    });

    models.trade_order_measure_weekly = db.define("youa_dm.trade_order_measure_weekly", {
      week_start:           Date,
      week_end:             Date,
      terminal_type:        String,
      cps_channel:          String,
      order_num:            Number,
      paid_order_num:       Number,
      member_num:           Number,
      paid_member_num:      Number,
      payment_amount:       Number,
      paid_payment_amount:  Number,
      pct:                  Number,
      etl_time:             Date,
      gross_margin:         Number
    },{
      id: "etl_time"
    });

    models.trade_order_measure_monthly = db.define("youa_dm.trade_order_measure_monthly", {
      create_month:         Date,
      terminal_type:        String,
      cps_channel:          String,
      order_num:            Number,
      paid_order_num:       Number,
      member_num:           Number,
      paid_member_num:      Number,
      payment_amount:       Number,
      paid_payment_amount:  Number,
      pct:                  Number,
      etl_time:             Date,
      gross_margin:         Number
    },{
      id: "etl_time"
    });

    models.trade_guider_kpi_weekly = db.define("youa_dm.trade_guider_kpi_weekly", {
      guider_code:          String,
      week_start:           Date,
      week_end:             Date,
      order_num:            Number,
      paid_order_num:       Number,
      member_num:           Number,
      paid_member_num:      Number,
      payment_amount:       Number,
      paid_payment_amount:  Number,
      pct:                  Number,
      etl_time:             Date
    },{
      id: "etl_time"
    });

    models.trade_guider_kpi_monthly = db.define("youa_dm.trade_guider_kpi_monthly", {
      guider_code:          String,
      create_month:         Date,
      order_num:            Number,
      paid_order_num:       Number,
      member_num:           Number,
      paid_member_num:      Number,
      payment_amount:       Number,
      paid_payment_amount:  Number,
      pct:                  Number,
      etl_time:             Date
    },{
      id: "etl_time"
    });

    models.trade_prt_sale_daily = db.define("youa_dm.trade_prt_sale_daily", {
      create_date:          Date,
      single_code:          String,
      single_name:          String,
      category_name:        String,
      payable_fee:          Number,
      qty:                  Number,
      etl_time:             Date
    },{
      id: "etl_time"
    });

    models.trade_prt_sale_weekly = db.define("youa_dm.trade_prt_sale_weekly", {
      week_start:           Date,
      week_end:             Date,
      single_code:          String,
      single_name:          String,
      category_name:        String,
      payable_fee:          Number,
      qty:                  Number,
      etl_time:             Date
    },{
      id: "etl_time"
    });

    models.trade_prt_sale_monthly = db.define("youa_dm.trade_prt_sale_monthly", {
      create_month:         Date,
      single_code:          String,
      single_name:          String,
      category_name:        String,
      payable_fee:          Number,
      qty:                  Number,
      etl_time:             Date
    },{
      id: "etl_time"
    });

    models.youa_bi_user_member = db.define('youa_bi_user.youa_bi_user_member', {
      username:             String,
      password:             String,
      gmt_create:           Date,
      gmt_modified:         Date,
      isdelete:             Boolean,
      id:                   Number
    },{
      id: 'id'
    });

    models.customer_distribute = db.define('youa_dm.customer_distribute', {
      type:                 String,
      type_detail:          String,
      num:                  Number
    }, {
      id: 'type'
    });

    models.customer_register_daily = db.define('youa_dm.customer_register_daily', {
      reg_date:             Date,
      terminal_type:        String,
      reg_num:              Number,
      etl_time:             Date
    }, {
      id: 'etl_time'
    });

    models.fact_member = db.define('youa_dm.fact_member', {
      member_id:            String,
      register_time:        Date,
      last_login_time:      Date,
      receiver_name:        String,
      receiver_cert_no:     String,
      sex:                  String,
      birthday:             String,
      receiver_mobile:      String,
      receiver_province:    String,
      receiver_city:        String,
      terminal_type:        String,
      etl_time:             Date,
      ages:                 Number
    },{
      id: 'member_id'
    })

    next();
  }
}));

app.use('/', routes);
app.use('/user', user);
app.use('/order', order);
app.use('/kpi', kpi);
app.use('/product', product);
app.use('/member', member);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
